package com.example.weather

//import androidx.compose.ui.tooling.data.EmptyGroup.name

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageButton
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.weather.ui.theme.WeatherTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import kotlin.math.log


@Suppress("UNREACHABLE_CODE")
class MainActivity : ComponentActivity() ,View.OnClickListener{
    private val API_KEY = "52fa2d8d4aabdb7036eb2bff4d223fac"
    private val BASE_URL = "https://apis.tianapi.com/tianqishiju/index"

    private lateinit var text_tianqi:TextView;

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main);
        val btnStart: ImageButton = findViewById(R.id.btn_start);
        text_tianqi = findViewById(R.id.text_tianqi)
        text_tianqi.setTextAppearance(R.style.MyTextStyle)//自定义textview样式
        btnStart.setOnClickListener(this);
    }
    @Composable
    fun Greeting(name: String, modifier: Modifier = Modifier) {
        Text(
            text = "name $name!",
            modifier = modifier
        )
    }
    @Preview(showBackground = true)
    @Composable
    fun GreetingPreview() {
        WeatherTheme {
            Greeting("Android")
        }
    }
    override fun onClick(p0: View?) {
        GlobalScope.launch(Dispatchers.IO) {
            try {
                val city = "New York" // 要查询的城市
                val url = URL((BASE_URL + "?key=" + API_KEY).toString() + "&q=" + city)
                val connection = url.openConnection() as HttpURLConnection
                val reader = BufferedReader(InputStreamReader(connection.inputStream))
                val response = StringBuilder()
                var line: String?
                while (reader.readLine().also { line = it } != null) {
                    response.append(line)
                }
                reader.close()
                val jsonResponse = response.toString()
                withContext(Dispatchers.Main) {
                    text_tianqi.setText(jsonResponse)
                }
                Log.e("TAG", "成功 ++++++++++++ ")
            } catch (e: IOException) {
                e.printStackTrace();
                Log.e("TAG", "失败 ++++++++++++ ")
            }
        }
    }
}
